<template>
    <div class="login">
        <div class="loginBox">
          <div class="logo">
            <t-image :src="logoImageUrl"></t-image>
            <span class="logoText">CQIAE</span>
          </div>
          <div class="formBox">
            <p class="welcome">欢迎登陆DK-Cloud质检</p>
            <t-form
                ref="form"
                :data="formData"
                :rules="rules"
                :label-align="formData.labelAlign"
                :colon="true"
                :label-width="100"
                @submit="onSubmit"
            >
              <t-form-item label="账号" name="account">
                <div :class="isShowOut1 ? 'outBorder': ''">
                  <t-input
                      v-model="formData.account"
                      ref="accountInput"
                      clearable
                      placeholder="请输入账户名"
                      @focus="onFocus1"
                      @blur="onBlur1"
                  >
                  </t-input>
                </div>
              </t-form-item>

              <t-form-item label="密码" name="password">
                <div :class="isShowOut2 ? 'outBorder': ''">
                  <t-input
                      v-model="formData.password"
                      type="password"
                      clearable
                      placeholder="请输入密码"
                      @focus="onFocus2"
                      @blur="onBlur2"
                  >
                  </t-input>
                </div>
              </t-form-item>

              <t-form-item label="" name="course">
                <t-checkbox v-model="formData.remember">记住我的密码</t-checkbox>
              </t-form-item>

              <t-form-item>
                <t-button :disabled="formData.password ==='' || formData.account ===''" type="submit" >登录</t-button>
              </t-form-item>
            </t-form>
          </div>
        </div>
        <div class="imgBox">
          <div class="bgImg">
            <t-image :src="rightImageUrl"  :style="{ width: '100%', height: '100%' }" fit="cover"></t-image>
          </div>
        </div>
        <verify-code v-if="isVerify" @verifyOperation="verifyOperation"></verify-code>
    </div>
</template>

<script setup>
import { getCurrentInstance, onBeforeMount, ref, reactive, onMounted, nextTick } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next';
import { DesktopIcon, LockOnIcon } from 'tdesign-icons-vue-next';
import { useUserStore } from '@/pinia/user.js'
import { useRoute, useRouter} from "vue-router";
import { login, authInfo } from '@/api/login.js'
import { encrypt } from "@/utils/jsencrypt"
import cache from '@/utils/cache.js'
import VerifyCode from './VerifyCode.vue'
import { chain } from 'lodash';
import { useMenuList } from '@/pinia/menu.js'
import {menuNav} from "../../api/system/menu";
import auth from '@/utils/auth.js'

const route = useRoute()
const router = useRouter()
// img | svg
const logoImageUrl = ref('')
const rightImageUrl = ref('')
let codeUrl = ref('')
let codeUrl1 = ref('')
let isVerify = ref(false)
let verifyImg = ref(null)
let formData = reactive({
  labelAlign: 'top',
  account: '',
  password: '',
  remember: false
});
onBeforeMount(() => {
  logoImageUrl.value = new URL(`@/assets/file/svg/logo.svg`, import.meta.url).href
  rightImageUrl.value = new URL(`@/assets/big.png`, import.meta.url).href
  if(cache.getLocalstorage('login')) {
    formData.account = JSON.parse(cache.getLocalstorage('login')).account
    formData.password = JSON.parse(cache.getLocalstorage('login')).password
    formData.remember = JSON.parse(cache.getLocalstorage('login')).remember
  }
});
let pageInstance = getCurrentInstance()
onMounted(() => {
  pageInstance.refs.accountInput.$el.querySelector('input').focus()
})
// form
const rules = {
  account: [
    { required: true, message: '账号必填', type: 'error', trigger: 'blur' },
    { required: true, message: '账号必填', type: 'error', trigger: 'change' },
    { whitespace: true, message: '账号不能为空' },
  ],
  password: [
    { required: true, message: '密码必填', type: 'error' },
    { whitespace: true, message: '密码不能为空' },
  ],
};

const isShowOut1 = ref(false)
const isShowOut2 = ref(false)
const onFocus1 = (val, ctx) => {
  isShowOut1.value = true
  isShowOut2.value = false
}
const onBlur1 = (val, ctx) => {
  isShowOut1.value = false
  isShowOut2.value = false
}
const onFocus2 = (val, ctx) => {
  isShowOut1.value = false
  isShowOut2.value = true
}
const onBlur2 = (val, ctx) => {
  isShowOut1.value = false
  isShowOut2.value = false
}

const onSubmit = ({ validateResult, firstError }) => {
  if (validateResult === true) {
    // MessagePlugin.success('提交成功');
    console.log('formData', formData)
    // router.push('/home')
    isVerify.value = true
  } else {
    console.log('Validate Errors: ', firstError, validateResult);
    MessagePlugin.warning(firstError);
  }
};

//验证页面的刷新和关闭事件
const verifyOperation = (type, data) => {
  if(type == 'refresh') {
    if(formData.remember) {
      cache.setLocalstorage('login', formData)
    } else {
      if(cache.getLocalstorage('login')) cache.removeLocalstorage('login')
    }
    data.username = formData.account
    data.password = encrypt(formData.password)
    data.code = encrypt(data.code.toString())
    const user = useUserStore()
    user.userLogin(data).then(async (res) => {
      if(res === 'loginSuccess') {
        try {
          // 获取路由信息
          const list = await menuNav()

          useMenuList().$patch((state) => {
            state.asyncRoutes = list.data
          })
          useMenuList().updateRouteList(JSON.parse(JSON.stringify(list.data))).then(async _ => {
            // 登录的机构信息
            await authInfo().then(res => {
              cache.setLocalstorage('authInfo', res.data)
              user.$patch({ authInfo: res.data })
              router.push('/home')
            })
          })
        } catch (error) {
          // 清除token 防止刷新进入系统
          auth.removeToken()
          verifyImg = {}
          isVerify.value = false
        }
      }
    }).catch(error => {
      isVerify.value = false
    })
  }
  if(type == 'close') {
    verifyImg = {}
    isVerify.value = false
  }
}
</script>

<style lang="scss" scoped>
.login {
  //height: 100vh;
  width: 100vw;
  //display: flex;
  position: relative;
  .loginBox {
    position: absolute;
    top: 0;
    display: inline-block;
    //width: 735px;
    width: 50%;
    height: 100vh;
    .logo {
      margin-left: 49px;
      margin-top: 56px;
      height: 64px;
      position: relative;
      :deep(.t-image__wrapper) {
        width: 64px;
        height: 64px;
        display: inline-block;
        margin-right: 16px;
      }
      .logoText {
        font-size: 36px;
        font-weight: 500;
        color: rgba(30, 117, 254, 1);
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
      }
    }
    .formBox {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      //margin: 111px auto;
      width: 358px;
      //background-color: red;
      .welcome {
        font-size: 30px;
        font-weight: 600;
        letter-spacing: 0;
        line-height: 38px;
        color: rgba(30, 117, 254, 1);
        text-align: left;
        vertical-align: top;
        margin-bottom: 24px;
      }
      :deep(.t-form__label--colon label::after) {
        display: none;
      }
      :deep(.t-form__label) {
        font-size: 16px;
        font-weight: 500;
        letter-spacing: 0;
        line-height: 24px;
        color: rgba(51, 63, 81, 1);
        text-align: left;
      }

      :deep(.t-form__item:nth-child(1)) {
        .t-form__controls-content {
          width: 364px;
          height: 52px;
          align-items: center;
          justify-content: center;
        }
      }
      :deep(.t-form__item:nth-child(2)) {
        .t-form__controls-content {
          width: 364px;
          height: 52px;
          align-items: center;
          justify-content: center;
        }
      }

      .outBorder {
        width: 364px;
        height: 52px;
        border-radius: 12px;
        border: 3px solid rgba(171, 203, 255, 1);
        box-sizing: border-box;
        :deep(.t-input) {
          border: 1px solid rgba(0, 87, 227, 1);
        }
      }
      :deep(.t-input) {
        width: 358px;
        height: 46px;
        border-radius: 8px;
        opacity: 1;
        background: rgba(255, 255, 255, 1);
        border: 1px solid rgba(221, 225, 230, 1);
        box-shadow: 0 1px 2px  rgba(0, 0, 0, 0.05);
        display: flex;
        justify-content: flex-start;
        align-items: center;
        padding: 10px 14px 10px 14px;
      }
      :deep(.t-input:hover) {
        border: 1px solid rgba(0, 87, 227, 1);
      }
      :deep(.t-checkbox:hover) {
        .t-checkbox__input {
          border-color: rgba(30, 117, 254, 1) !important;
        }
      }
      :deep(.t-is-checked) {
        .t-checkbox__input {
          border: none;
          background-color: rgba(30, 117, 254, 1);
        }
        .t-checkbox__input::after {
          top: 7px;
          left: 4px;
        }
      }
      :deep(.t-button) {
        width: 358px;
        height: 46px;
        opacity: 1;
        border-radius: 6px;
        background: rgba(30, 117, 254, 1);
        box-shadow: 0 1px 2px  rgba(105, 81, 255, 0.05);
        display: flex;
        justify-content: center;
      }
      :deep(.t-is-disabled) {
        background: #ecf2fe!important;
        border-color: #ecf2fe;
        font-size: 16px;
        font-weight: 500;
        color: #fff;
      }
    }
  }
  .imgBox {
    position: absolute;
    right: 0;
    display: inline-block;
    width: 50%;
    opacity: 1;
    height: 100vh;
    .bgImg {
      height: 100%;
      overflow: hidden;
    }
  }
}
</style>
